package com.JUC.cha03.sec03;

import java.util.concurrent.*;

public class FutureThreadPoolDemo {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        // 3个任务，目前开启多个异步线程来处理，请问耗时多少？

        // 创建线程池，避免每次new Thread造成JVM垃圾回收

        long startTime = System.currentTimeMillis();

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        FutureTask futureTask1 = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(500);
            return "task1 over";
        });
        threadPool.submit(futureTask1);

        FutureTask futureTask2 = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(400);
            return "task2 over";
        });
        threadPool.submit(futureTask2);

        System.out.println(futureTask1.get());
        System.out.println(futureTask1.get());

        TimeUnit.MILLISECONDS.sleep(300);

        long endTime = System.currentTimeMillis();
        System.out.println("---- costTime：" + (endTime - startTime) + "毫秒");

        threadPool.shutdown();


    }

    private static void m1() throws InterruptedException {

        // 3个任务，目前只有一个线程main来处理，请问耗时多少？

        long startTime = System.currentTimeMillis();

        TimeUnit.MILLISECONDS.sleep(500);
        TimeUnit.MILLISECONDS.sleep(400);
        TimeUnit.MILLISECONDS.sleep(300);

        long endTime = System.currentTimeMillis();
        System.out.println("---- costTime：" + (endTime - startTime) + "毫秒");
        System.out.println(Thread.currentThread().getName() + "---- end");
    }
}
